﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Windows.Input;

namespace CLVisionMES
{
    [Serializable]
    internal class DataGridStruct 
    {
        //存储加入DataGrid的元素key值，用于判断是否重名
        public HashSet<string> KeysHashSet { get; set; }
        public ObservableCollection<DataGridItemStruct> DataGridItemStructs { get; set; }
    
        public DataGridStruct()
        {
            DataGridItemStructs = new ObservableCollection<DataGridItemStruct>();
            KeysHashSet = new HashSet<string>();
            //元素 集合有变化时，防止重名
            DataGridItemStructs.CollectionChanged += (sender, e) =>
            {
                if (e.Action == NotifyCollectionChangedAction.Add)
                {
                    foreach (DataGridItemStruct newItem in e.NewItems)
                    {
                        string value = newItem.Key.ToString();
                        while (true)
                        {
                            if (KeysHashSet.Add(value))
                            {
                                newItem.Key = value;
                                break;
                            }
                            value = value + "_copy";
                        }
                    }
                }
            };
        }

        public DataGridStruct Clone()
        {
            // 创建一个新的 DataGridStruct 对象
            var cloned = new DataGridStruct
            {
                KeysHashSet = new HashSet<string>(this.KeysHashSet)
            };

            // 递归克隆 DataGridItemStructs 集合
            cloned.DataGridItemStructs = new ObservableCollection<DataGridItemStruct>();
            foreach (var item in this.DataGridItemStructs)
            {
                cloned.DataGridItemStructs.Add(item.Clone());
            }

            return cloned;
        }
    }
   
}
